<template>
  <div style="width: 100%; height: 100%">

    <!-- v-on="gridEvents" overflow: hidden -->
    <vxe-grid ref="tableRef" v-bind="gridOptions">
      <template #toolbar_buttons>
      </template>
      <template #inquiryStatus_slot="{ row }">
        <Tag :color="getOrderStatus(row.inquiryStatus)">{{ row.inquiryStatus }}</Tag>

      </template>

      <template #action="{ row }">
        <TableAction outside :actions="getActions(row)" />
      </template>


    </vxe-grid>


    <FormModal @register="register" @success="handleSuccess" />
    <EditFormModal @register="orderModal[0]" @success="handleSuccess"></EditFormModal>


  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '@/components/Table';
import {
  orderList, orderStatus, orderRemove, orderCancel
} from '@/api/heng/dkn';
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';
import {
  vxeTableColumns,
  vxeTableFormSchema,
} from './role.data';

import { Tag, Descriptions, DescriptionsItem } from 'ant-design-vue';
import { reactive, ref, unref, onMounted, h } from 'vue';
import { useUserStore } from '@/store/modules/user';
import FormModal from './FormModal.vue';
import EditFormModal from './EditFormModal.vue';
import { useMessage } from '@/hooks/web/useMessage';
import { useModal } from '@/components/Modal';
import { Modal, Tooltip, Button, Timeline, TimelineItem, MonthPicker } from 'ant-design-vue';
import { ClockCircleOutlined } from '@ant-design/icons-vue';

defineOptions({ name: 'MouldList' });
const { createMessage } = useMessage();
const userStore = useUserStore();

const [register, { openModal, closeModal }] = useModal();
const orderModal = useModal();
const loading = ref(false);
const visible = ref(false);
const applyViewShow = ref(false);

const totalObj = ref({ salesmanDeptList: [] })
const totalTitle = ref("");
const applyHistoryList = ref([]);

const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },
  exportConfig: {},
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
      // queryAll: async ({ form }) => {
      //   return await demoListApi(form);
      // },
    },
  },
});

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field + 'Like'] = value;
    });
  }
  // console.log("----json:", json);
  // ywApproveList xftList
  return orderList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  }).then((res) => {
    return res;
  });
}

const findList = (filterList?: VxeTableDefines.FilterCheckedParams<any>[]) => {
  gridOptions.loading = true;
  // 模拟接口
  let queryJson = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      queryJson[field + 'Like'] = value;
    });
  }

  return new Promise<any[]>((resolve) => {
    let pp = {
      page: { currentPage: 1, pageSize: 20 },
      form: queryJson,
    };

    gridOptions.proxyConfig.ajax.query(pp).then((res) => {
      gridOptions.loading = false;
      let resultObj = {
        result: res.data.list,
        page: {
          total: res.data.totalResult,
        },
      };

      resolve(res);
    });
  });
};



function queryOrderStatus(res) {
  let list = res.data.list;
  let t_list = tableRef.value.getTableData().tableData;

  for (let i = 0; i < list.length; i++) {
    let item = list[i];
    let t_item = t_list[i];

    orderStatus({ inquiryCode: item.inquiryCode })
      .then((re) => {
        // console.log("---re::");
        if (re) {
          let json = re.data;
          // console.log(json);
          if (t_item) {
            t_item.inquiryStatus = json.inquiry_status;
            t_item.remark = json.message;
            tableRef.value?.setEditRow(t_item);
          }
        }

      });
  }


}

function getOrderStatus(inquiryStatus) {
  let color = "";
  switch (inquiryStatus) {
    case "ordered":
      color = "green";
      break;
    case "rejected":
      color = "red";
      break;
  }
  return color;
}

function applyViewOpen() {
  applyViewShow.value = true;
}

function applyViewClose() {
  applyViewShow.value = false;
}







function getActions(record) {
  let arr = [
    {
      // icon: 'clarity:note-edit-line',
      label: '查看物料',
      onClick: handleEdit.bind(null, record),
    },
  ];
  if (record.orderCode) {
    // let t1 = {
    //   // icon: 'clarity:note-edit-line',
    //   label: '修改',
    //   onClick: editOrder.bind(null, record),
    // };


    // arr.push(t1);

    let t = {
      // icon: 'ant-design:delete-outlined',
      label: '取消',
      color: 'error',
      popConfirm: {
        title: '是否取消？',
        placement: 'left',
        confirm: handleCancel.bind(null, record),
      },
    };
    arr.push(t);
  } else {
    let t2 = {
      // icon: 'ant-design:delete-outlined',
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否删除？',
        placement: 'left',
        confirm: handleClose.bind(null, record),
      },
    };
    arr.push(t2)
  }


  return arr;
}

function handleCreate() {
  openModal(true, {
    isUpdate: false,
  });
}

function handleEdit(record: Recordable) {
  openModal(true, {
    record
  });
}


function editOrder(record: Recordable) {
  orderModal[1].openModal(true, record);

}

function handleCancel(record: Recordable) {
  orderCancel(record)
    .then((res) => {
      if (res.code == 200) {
        createMessage.success(res.message);
        tableRef.value.commitProxy('reload');
      } else {
        createMessage.error(res.message);
      }
    })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}

function handleClose(record: Recordable) {
  //console.log(record);

  orderRemove(record)
    .then((res) => {
      if (res.code == 200) {
        createMessage.success(res.message);
        tableRef.value.commitProxy('reload');

      } else {
        createMessage.error(res.message);

      }

    })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}




function handleSuccess() {
  tableRef.value.commitProxy('reload');
}





</script>
<style lang="less">
.isReturn_clazz {
  text-align: center;
  cursor: pointer;
}
</style>
